<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <el-button type="primary" :icon="Plus" @click="showTrademarkDialog"
          >添加</el-button
        >
      </div>
    </template>
    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="trademarkList"
      border
      style="width: 100%"
    >
      <el-table-column type="index" align="center" label="序号" width="180" />
      <el-table-column prop="tmName" label="品牌名" width="180" />
      <el-table-column label="品牌LOGO">
        <template v-slot="{ row }">
          <img :src="row.logoUrl" alt="" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button
            title="修改"
            size="small"
            type="warning"
            :icon="Edit"
            @click="editTrademark(row)"
          ></el-button>
          <el-button
            title="删除"
            size="small"
            type="danger"
            :icon="Delete"
            @click="removeTrademark(row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 6, 9, 12]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout=" prev, pager, next, jumper,->, sizes,total,"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 对话框 -->

    <el-dialog
      v-model="dialogFormVisible"
      :title="`${trademark.id ? '修改' : '添加'}品牌`"
    >
      <!--Form表单项 -->
      <el-form
        :model="trademark"
        ref="ruleFormRef"
        :rules="rules"
        :size="formSize"
      >
        <el-form-item
          label="品牌名"
          prop="tmName"
          label-width="90px"
          width="75%"
        >
          <el-input v-model="trademark.tmName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="品牌logo" prop="logoUrl" label-width="90px">
          <!--  <el-select v-model="form.region" placeholder="Please select a zone">
          <el-option label="Zone No.1" value="shanghai" />
          <el-option label="Zone No.2" value="beijing" />
        </el-select> -->

          <el-upload
            class="avatar-uploader"
            :action="`${BASE_URL}/admin/product/upload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademark.logoUrl"
              :src="trademark.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/jpeg/png等格式图片,且大小不能超过2M
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">{{
            trademark.id ? "修改" : "添加"
          }}</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>
<script lang="ts">
export default {
  name: "trademark",
};
</script>


<script lang="ts" setup>
import type {
  TradeMarkerList,
  TradeMarker,
} from "@/api/product/model/trademarkModel";

// 引入方请求方法
import {
  reqGetTrademarkListData,
  reqSaveTrademarkInfo,
  reqDeleteTrademarkInfo,
  reqUpdateTrademarkInfo,
} from "@/api/product/trademark";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import { onMounted, ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { UploadProps } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
// 对话框
// const imageUrl = ref("");
const dialogFormVisible = ref<Boolean>(false);
const formLabelWidth = "140px";
// 对话框 数据源
// const form = reactive<TradeMarker>({
//   logoUrl: "",
//   tmName: "",
// });
const trademarkInfo = () => {
  return {
    logoUrl: "",
    tmName: "",
  };
};

const trademark = reactive<TradeMarker>(trademarkInfo());

// 动态读取环境变量中的值
const BASE_URL = import.meta.env.VITE_API_URL;

// 给请求回来的数据创建接收变量
let trademarkList = ref<TradeMarkerList>([]);

// 分页器参数
let currentPage = ref<number>(1);
let pageSize = ref<number>(5);
const total = ref<number>(0);

const small = ref<Boolean>(false);
const disabled = ref<Boolean>(false);
const background = ref<Boolean>(false);

// 表单校验
const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
// 校验规则
const rules = reactive<FormRules>({
  tmName: [
    {
      required: true,
      message: "商品名不能为空,请输入你的商品名",
      trigger: "blur",
    },
    { min: 3, max: 5, message: "商品名长度只能为3-5个字符", trigger: "blur" },
  ],
  logoUrl: [
    {
      required: true,
      message: "请添加要上传的照片",
      trigger: "change",
    },
  ],
});

//加载效果
let loading = ref<Boolean>(true);
//1. 创建发送请求
const getTrademarkListData = async () => {
  const result = await reqGetTrademarkListData(
    currentPage.value,
    pageSize.value
  );
  // console.log(result);

  // 总信息条数
  total.value = result.total;

  // 加载效果影藏
  loading.value = false;

  trademarkList.value = result.records;
};

// 2.分页器函数 选项页数定义
const handleSizeChange = (val: number) => {
  // console.log(`${val} items per page`);
  pageSize.value = val;

  currentPage.value = 1;
  // 记载效果

  loading.value = true;

  // 重新发送请求
  getTrademarkListData();
};

//3. 当前页面改变
const handleCurrentChange = (val: number) => {
  // console.log(`current page: ${val}`);
  currentPage.value = val;

  loading.value = true;

  // 重新发送请求
  getTrademarkListData();
};

// 4.上传图片成功后要执行的函数
const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  // 将图片存储在服务器上的地址保存在logoUrl中显示图片
  trademark.logoUrl = response.data;

  // 清除表单验证
  ruleFormRef.value?.clearValidate(["logoUrl"]);
};

//5. 上传图片之前校验
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  // if (rawFile.type !== "image/jpeg") {
  // 限定传入图片的格式
  const imgTypes = ["image/jpeg", "image/png", "image/jpg", "image/jfif"];
  if (!imgTypes.includes(rawFile.type)) {
    ElMessage.error("上传照片把格式不正确");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("请传入大小小于2M的照片");
    return false;
  }
  return true;
};

// 6添加品牌请求
const getSaveTrademarkInfo = async () => {
  if (trademark.id) {
    // 修改商品信息
    await reqUpdateTrademarkInfo(trademark);
  } else {
    // 点击确认按钮发送请求添加商品
    await reqSaveTrademarkInfo(trademark);
  }
  // console.log("添加商品请求陈宫");
  ElMessage.success("添加品牌成功...");
  // 将对话框影藏
  dialogFormVisible.value = false;
  // 返回第一页参数
  currentPage.value = 1;
  // 发送请求重新获取数据
  getTrademarkListData();
};

// 7.请求完成时清除对话框内容(显示对话框)
function showTrademarkDialog() {
  // 清除框内内容
  // 将trademarkInfo找个对象中的属性,放到trademark这个空对象中
  Object.assign(trademark, trademarkInfo());
  // 我们使用是否有id来判断是添加还是修改 如果是修改那么他会带有id
  delete trademark.id;

  // 清除校验规则
  ruleFormRef.value?.clearValidate();

  // 显示对画框
  dialogFormVisible.value = true;
}
//8. 删除按钮删除指定信息
const removeTrademark = (row: TradeMarker) => {
  ElMessageBox.confirm(`你确定要删除${row.tmName}这个品牌`, "提示:", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      // 在此处发送请求
      await reqDeleteTrademarkInfo(row.id as Number);
      ElMessage({
        type: "success",
        message: "删除成功",
      });

      currentPage.value =
        trademarkList.value.length > 1
          ? currentPage.value
          : currentPage.value - 1;

      // 重新发送请求
      getTrademarkListData();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "删除失败",
      });
    });
};
// 9.修改商品信息
const editTrademark = (row: TradeMarker) => {
  Object.assign(trademark, row); // 注意 此时的row当中，是有id的
  // 显示对话框后去对下画框中书写逻辑
  dialogFormVisible.value = true;

  // 清除校验规则
  ruleFormRef.value?.clearValidate();
};

// 10.表单校验函数
const submitForm = async (formEl: FormInstance | undefined) => {
  // console.log("按钮事件执行", formEl);

  if (!formEl) return;
  await formEl?.validate((valid, fields) => {
    if (valid) {
      // console.log("submit!");
      if (trademark.id) {
        // 有id就是修改信息
        // 党校验成功是发送请求修改商品
        reqUpdateTrademarkInfo(trademark);
        ElMessage.success("修改品牌成功...");
      } else {
        // 发送请求添加上商品请求
        reqSaveTrademarkInfo(trademark);
        ElMessage.success("添加品牌成功...");
        // 跳转到第一页
        currentPage.value = 1;
      }

      // 请求发送成功关闭对话框
      dialogFormVisible.value = false;
      getTrademarkListData();
    } else {
      console.log("error submit!", fields);
    }
  });
};
// 在组价挂载时触发请求函数
onMounted(() => {
  getTrademarkListData();
});
</script>

<style scoped >
.el-input {
  width: 75%;
}
</style>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>